package com.tencent.wxcloudrun.controller;

import com.alibaba.fastjson.JSONObject;
import com.tencent.wxcloudrun.entity.UserAllInfo;
import com.tencent.wxcloudrun.entity.UserInfo;
import com.tencent.wxcloudrun.entity.UserInfoInformation;
import com.tencent.wxcloudrun.service.UserService;
import com.tencent.wxcloudrun.vo.JsonBean;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@ResponseBody
@CrossOrigin(originPatterns = "*",methods = {RequestMethod.GET,RequestMethod.POST})
public class UserController {
    @Autowired
    private UserService userService;

    /*
    * 获得所有用户信息
    *
    * */
    @GetMapping("/getUserList")
    public JsonBean getUserList(){
        JsonBean jsonBean = new JsonBean();
        jsonBean.setCmd("getUserList");
        try{
            jsonBean.setStatus(200);
            List<UserAllInfo> userAllInfoList = userService.getUserList();
            jsonBean.setData(userAllInfoList);
            return jsonBean;
        }catch (Exception e){
            e.printStackTrace();
            jsonBean.setStatus(-1);
            return jsonBean;
        }

    }
    //判断用户是否为已注册用户
    boolean isOldUser = false;
    //userinfo对象，用于下方方法的赋值
    UserInfo userInfo = new UserInfo();
    //获取用户手机号，前端回传code
    @GetMapping(value = "/getUserPhone")
    @ResponseBody
    public JsonBean getUserPhone(@RequestParam("code") String code){
        System.out.println(code);
        JsonBean jsonBean = new JsonBean();
        jsonBean.setCmd("getUserPhone");
        try {
            //返回手机号的json字符串
            JSONObject jsonObject = userService.getUserPhone(code);
            jsonBean.setStatus(200);
            jsonBean.setData(jsonObject);

            JSONObject jsonObject1 = jsonObject.getJSONObject("phone_info");
            String phone = jsonObject1.getString("phoneNumber");
            //打印手机号
            System.out.println(phone);
            //查询该手机号是否已经注册
            int i = queryUserPhone(phone);
            if(i != 0){
                System.out.println("该手机号已注册");
                isOldUser = true;
                userInfo.setPhoneNumber(phone);
            }else{
                System.out.println("该手机号未注册");
                isOldUser = false;
                //将手机号写入实体类中，存入数据库
                userInfo.setPhoneNumber(phone);
            }
            return jsonBean;
        }catch (Exception e){
            e.printStackTrace();
            jsonBean.setStatus(-1);
            return jsonBean;
        }
    }


    String session;
    String rawData;
    String signature;
    int userInfoId = 0;
    //用户登录
    @GetMapping("/UserLogin")
    @ResponseBody
    public JsonBean userLogin(@RequestParam("code")String code) {
        System.out.println(code);
        JsonBean jsonBean = new JsonBean();
        jsonBean.setCmd("userLogin");
        try {

            //将状态放置于json中
            jsonBean.setStatus(200);
            JSONObject jsonObject = userService.userLogin(code);
            jsonBean.setData(jsonObject);
            //会话KEY
            session = jsonObject.getString("session_key");
            //打印session
            System.out.println("session_key:"+session);
            //将session以及code写入实体类中
            userInfo.setSessionKey(session);
            userInfo.setCode(code);
            //判断用户是否为已注册用户
            //若true
            if(isOldUser){
                //更新该用户的sessionkey和code
                int isUpdateOk = userService.updateUserSessionAndCode(userInfo);
                System.out.println("isUpdateOK:"+isUpdateOk);
                /**
                *
                * 获取到该用户的用户ID
                * */
                int userId = userService.getUserId(userInfo.getPhoneNumber());
                userInfoId = userId;
            }else {
                //若false
                //将session以及code写入至数据库中
                int isOk = insertUserSession(userInfo);
                //打印isok的值
                System.out.println("isOK:"+isOk);
                //插入成功
                if (isOk==1){
                    //获取返回的主键值
                    userInfoId = userInfo.getId();
                    System.out.println("userInfoID:"+userInfoId);
                    //插入失败
                }else{
                    System.out.println("录入失败");
                }
            }

            return jsonBean;
        }catch (Exception e){
            e.printStackTrace();
            jsonBean.setStatus(-1);
            return jsonBean;
        }
    }
    //根据userInfoId保存用户的信息
    @GetMapping("/insertUserInfo")
    @ResponseBody
    public void insertUserInfo(@RequestParam("avatarUrl") String avatarUrl,@RequestParam("nickName") String nickName){
        UserInfoInformation userInfoInformation = new UserInfoInformation();
        userInfoInformation.setUid(userInfoId);
        userInfoInformation.setNickName(nickName);
        userInfoInformation.setAvatarUrl(avatarUrl);
        try {
            int isHaveUid = userService.queryUserInfoInformationUid(userInfoId);
            if(isHaveUid!=0){
                //如果该手机号的用户此前已经注册过并且有了详细信息，则更新详细信息
                int i = userService.updateUserInformation(userInfoInformation);
                System.out.println("更新"+i);
            }else{
                //如果仅为刚注册过但没有详细信息，则插入新的详细信息
                int i = userService.insertUserInfo(userInfoInformation);
                System.out.println("插入"+i);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    //更新用户填写的详细信息
    public JsonBean updateUserInfomation(String address,String sex,String name,String company,String email,String center,String department,String position){
        JsonBean jsonBean = new JsonBean();
        jsonBean.setCmd("updateUserInfomation");
        try {
            UserInfoInformation userInfoInformation = new UserInfoInformation();
            userInfoInformation.setCenter(center);
            userInfoInformation.setCompany(company);
            userInfoInformation.setDepartment(department);
            userInfoInformation.setEmail(email);
            userInfoInformation.setPosition(position);
            userInfoInformation.setName(name);
            userInfoInformation.setAddress(address);
            userInfoInformation.setSex(sex);
            int u = userService.updateUserInformation(userInfoInformation);
            if(u!=0){
                jsonBean.setStatus(200);
                jsonBean.setData("success");
            }else{
                jsonBean.setStatus(201);
                jsonBean.setData("fail");
            }
            return jsonBean;
        }catch (Exception e){
            e.printStackTrace();
            jsonBean.setStatus(-1);
            jsonBean.setData("exception");
            return jsonBean;
        }
    }
    //根据手机号查询用户的昵称等信息
    @GetMapping("/queryUser")
    @ResponseBody
    public JsonBean queryUser(@RequestParam("phoneNumber")String phoneNumber){
        JsonBean jsonBean = new JsonBean();
        jsonBean.setCmd("queryUser");
        System.out.println("queryUserPhone:"+phoneNumber);
        try {
            UserAllInfo userAllInfo = userService.getUser(phoneNumber);
            jsonBean.setStatus(200);
            jsonBean.setData(userAllInfo);
            System.out.println(userAllInfo.getNickName());
            return jsonBean;
        }catch (Exception e){
            e.printStackTrace();
            jsonBean.setStatus(-1);
            return jsonBean;
        }
    }
    //获取用户rawData
    @GetMapping("/giveUserRawDataAndSignature")
    @ResponseBody
    public void getUserRawData(@RequestParam("rawData") String rawData,@RequestParam("signature")String signature){
        this.rawData = rawData;
        this.signature = signature;
        System.out.println("rawData:"+this.rawData);
        System.out.println("signature:"+this.signature);
    }
    //加密"rawData+SessionKey"以对比signature
    public void AESRawDataAndSessionKey(String session,String rawData,String signature){

    }


    //录入用户的session以及code
    public int insertUserSession(UserInfo userInfo){
        int isOk = 0;
        try {
            isOk = userService.insertUserSessionKey(userInfo);
            return isOk;
        }catch (Exception e){
            e.printStackTrace();
            return isOk;
        }

    }
    //查询数据库内是否有该用户
    public int queryUserPhone(String userPhone){
        int i = 0;
        try {
            i = userService.queryUserPhone(userPhone);
            System.out.println("是否有该用户:"+i);
            return i;
        }catch (Exception e){
            e.printStackTrace();
            i = 0;
            return i;
        }
    }
}
